package com.hehe.library.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;

import android.os.AsyncTask;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hehe.library.MyApplication;
import com.hehe.library.R;

import io.realm.Realm;

/**
 * 注册页
 * 需要输入手机号,名字,密码
 * 手机号需为11位(暂只考虑中国大陆用户)
 * 密码最短6位
 */
public class RegisterActivity extends AppCompatActivity  {



    /**
     * 用户注册任务.
     */
    private UserRegisterTask mAuthTask = null;

    // UI引用
    private AutoCompleteTextView mPhonelView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;
    private EditText mNameView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mPhonelView = (AutoCompleteTextView) findViewById(R.id.phone_register);

        mNameView = (EditText) findViewById(R.id.name_register);


        mPasswordView = (EditText) findViewById(R.id.password_register);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptRegister();
                    return true;
                }
                return false;
            }
        });

        Button mPhoneSignInButton = (Button) findViewById(R.id.register);
        mPhoneSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptRegister();
            }
        });

        mLoginFormView = findViewById(R.id.register_form);
        mProgressView = findViewById(R.id.register_progress);
    }




    /**
     * 尝试注册
     * 验证手机号\昵称\用户名是否合格
     *
     */
    private void attemptRegister() {
        if (mAuthTask != null) {
            return;
        }

        // 清空错误提示
        mPhonelView.setError(null);
        mPasswordView.setError(null);
        mNameView.setError(null);

        // 拿到用户的输入值
        String phone = mPhonelView.getText().toString();
        String password = mPasswordView.getText().toString();
        String name = mNameView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // 验证密码
        if (!isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }
        //验证名字
        if (TextUtils.isEmpty(name)) {
            mNameView.setError(getString(R.string.error_field_required));
            focusView = mNameView;
            cancel = true;
        }

        // 验证手机号
        if (TextUtils.isEmpty(phone)) {
            mPhonelView.setError(getString(R.string.error_field_required));
            focusView = mPhonelView;
            cancel = true;
        } else if (!isPhoneValid(phone)) {
            mPhonelView.setError(getString(R.string.error_invalid_phone));
            focusView = mPhonelView;
            cancel = true;
        }

        if (cancel) {
            //发现错误,取消登录
            focusView.requestFocus();
        } else {
            //尝试注册
            showProgress(true);
            mAuthTask = new UserRegisterTask(phone, name,password);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isPhoneValid(String phone) {
        //手机号11位
        return phone.length() == 11;
    }

    private boolean isPasswordValid(String password) {
        //密码长度至少6位
        return password.length() > 5;
    }

    /**
     * 显示过程动画
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }





    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserRegisterTask extends AsyncTask<Void, Void, Boolean> {

        private final String mPhone;
        private final String mName;
        private final String mPassword;

        UserRegisterTask(String email,String name, String password) {
            mPhone = email;
            mPassword = password;
            mName = name;

        }

        @Override
        protected Boolean doInBackground(Void... params) {

            try {
                // 模拟服务器,等待2秒
                Thread.sleep(2000);
                Realm realm = Realm.getDefaultInstance();//获取Realm实例
                realm.beginTransaction();//开始传输
                UserInfoEntity userInfoEntity = realm.createObject(UserInfoEntity.class);
                userInfoEntity.setPhone(mPhone);
                userInfoEntity.setUsername(mName);
                userInfoEntity.setPassword(mPassword);
                realm.commitTransaction();
            } catch (InterruptedException e) {
                return false;
            }

            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                finish();
                //验证成功,跳转主页
                MyApplication.getUserInfo().setPhone(mPhone);
                Intent intent = new Intent(RegisterActivity.this,MainActivity.class);
                startActivity(intent);


            } else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

